using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Collections.Generic;

namespace FreeFlow.Administration
{
	/// <summary>
	/// A collection of scripts.
	/// </summary>
  public sealed class ScriptCollection : DatabaseAware, IEnumerable, IEnumerable<Script>, IBindingList, IRefreshable
	{
    private List<Script> scriptsList;
    private Map map;
    private Procedure procedure;
    /// <summary>
    /// Initializes a new instance of the <see cref="ScriptCollection"/> class for the specified map.
    /// </summary>
    /// <param name="server">The server.</param>
    /// <param name="map">The map.</param>
		public ScriptCollection(Server server, Map map) : base(server)
		{
      this.map = map;
		}

    /// <summary>
    /// Initializes a new instance of the <see cref="ScriptCollection"/> class for the specified procedure.
    /// </summary>
    /// <param name="server">The server.</param>
    /// <param name="procedure">The procedure.</param>
    public ScriptCollection(Server server, Procedure procedure) : base(server)
    {
      this.procedure = procedure;
    }

    private void ReadScripts()
    {
      if (scriptsList == null)
      {
        string name;
        AttachmentType type;
        if (map != null)
        {
          name = map.Name;
          type = AttachmentType.Map;
        }
        else if (procedure != null)
        {
          name = procedure.Name;
          type = AttachmentType.Procedure;
        }
        else
          throw new FreeFlowException("Unexpected call configuration");

        scriptsList = new List<Script>();
        using (IDataReader reader = Server.ExecuteReader(
          string.Format("SELECT * FROM eAttachment WHERE eKey LIKE '{0}\t{1}\t%' AND " +
          "(eKey LIKE '%.js' OR eKey LIKE '%.jsn' OR eKey LIKE '%.vbs') ", 
          (int)type, name)))
        {
          while (reader.Read()) 
          {
            Script script = new Script(Server, reader);
            scriptsList.Add(script);
          }
        }
      }
    }

    /// <summary>
    /// Gets the number of scripts in this collection.
    /// </summary>
    public int Count
    {
      get
      {
        ReadScripts();
        return scriptsList.Count;
      }
    }

    /// <summary>
    /// Gets the <see cref="Script"/> at the specified index.
    /// </summary>
    public Script this[int index]
    {
      get
      {
        ReadScripts();
        return (Script)scriptsList[index];
      }
    }

    #region IEnumerable Members

    IEnumerator IEnumerable.GetEnumerator()
    {
      ReadScripts();
      return scriptsList.GetEnumerator();
    }

    #endregion
    #region IEnumerable<Script> Members

    /// <summary>
    /// Returns an enumerator that iterates through the collection.
    /// </summary>
    /// <returns>
    /// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection.
    /// </returns>
    public IEnumerator<Script> GetEnumerator()
    {
      ReadScripts();
      return scriptsList.GetEnumerator();
    }

    #endregion
    #region IBindingList Members

    void IBindingList.ApplySort(PropertyDescriptor property, ListSortDirection direction)
    {
      ReadScripts();
      sortProperty = property;
      sortDirection = direction;
      scriptsList.Sort(new Comparer<Script>(sortProperty, sortDirection));
    }

    private PropertyDescriptor sortProperty;
    PropertyDescriptor IBindingList.SortProperty
    {
      get
      {
        return sortProperty;
      }
    }

    bool IBindingList.SupportsSorting
    {
      get
      {
        return true;
      }
    }

    bool IBindingList.IsSorted
    {
      get
      {
        return (sortProperty != null);
      }
    }

    void IBindingList.RemoveSort()
    {
      sortProperty = null;
    }

    private ListSortDirection sortDirection;
    ListSortDirection IBindingList.SortDirection
    {
      get
      {
        return sortDirection;
      }
    }

    #region not implemented 
    int IBindingList.Find(PropertyDescriptor property, object key)
    {
      return 0;
    }

    bool IBindingList.AllowRemove
    {
      get
      {
        return false;
      }
    }

    bool IBindingList.SupportsSearching
    {
      get
      {
        return false;
      }
    }

    private ListChangedEventHandler listChanged;
    event ListChangedEventHandler IBindingList.ListChanged
    {
      add { listChanged += value; }
      remove { listChanged -= value; }

    }

    bool IBindingList.SupportsChangeNotification
    {
      get
      {
        return false;
      }
    }

    object IBindingList.AddNew()
    {
      return null;
    }

    bool IBindingList.AllowEdit
    {
      get
      {
        return false;
      }
    }

    void IBindingList.RemoveIndex(PropertyDescriptor property)
    {
    }

    void IBindingList.AddIndex(PropertyDescriptor property)
    {
    }

    bool IBindingList.AllowNew
    {
      get
      {
        return false;
      }
    }

    #endregion

    #endregion
    #region IList Members

    /// <summary>
    /// Gets a value indicating whether the <see cref="T:System.Collections.IList"/> is read-only.
    /// </summary>
    public bool IsReadOnly
    {
      get
      {
        return true;
      }
    }

    object IList.this[int index]
    {
      get
      {
        ReadScripts();
        return scriptsList[index];
      }
      set
      {
        throw new NotSupportedException(readOnlyListMessage);
      }
    }

    void IList.RemoveAt(int index)
    {
      throw new NotSupportedException(readOnlyListMessage);
    }

    void IList.Insert(int index, object value)
    {
      throw new NotSupportedException(readOnlyListMessage);
    }

    void IList.Remove(object value)
    {
      throw new NotSupportedException(readOnlyListMessage);
    }

    /// <summary>
    /// Determines whether the <see cref="T:System.Collections.IList"/> contains a specific value.
    /// </summary>
    /// <param name="value">The <see cref="T:System.Object"/> to locate in the <see cref="T:System.Collections.IList"/>.</param>
    /// <returns>
    /// 	<see langword="true"/> if the <see cref="T:System.Object"/>
    /// is found in the <see cref="T:System.Collections.IList"/>; otherwise, <see langword="false"/>.
    /// </returns>
    public bool Contains(object value)
    {
      ReadScripts();
      return scriptsList.Contains((Script)value);
    }

    void IList.Clear()
    {
      throw new NotSupportedException(readOnlyListMessage);
    }

    /// <summary>
    /// Determines the index of a
    /// specific item in the <see cref="T:System.Collections.IList"/>.
    /// </summary>
    /// <param name="value">The <see cref="T:System.Object"/> to locate in the <see cref="T:System.Collections.IList"/>.</param>
    /// <returns>
    /// The index of <paramref name="value"/> if found in the list; otherwise, -1.
    /// </returns>
    public int IndexOf(object value)
    {
      ReadScripts();
      return scriptsList.IndexOf((Script)value);
    }

    int IList.Add(object value)
    {
      throw new NotSupportedException(readOnlyListMessage);
    }

    /// <summary>
    /// Gets a value indicating whether the <see cref="T:System.Collections.IList"/> has a fixed size.
    /// </summary>
    public bool IsFixedSize
    {
      get
      {
        return true;
      }
    }

    #endregion
    #region ICollection Members

    /// <summary>
    /// Gets a value
    /// indicating whether access to the <see cref="T:System.Collections.ICollection"/> is synchronized
    /// (thread-safe).
    /// </summary>
    public bool IsSynchronized
    {
      get
      {
        return false;
      }
    }
  
    void ICollection.CopyTo(Array array, int index)
    {
      CopyTo((Script[])array, index);
    }

    /// <summary>
    /// Copies the elements of
    /// the <see cref="T:System.Collections.ICollection"/> to an <see cref="T:System.Array"/>, starting at a particular <see cref="T:System.Array"/> index.
    /// </summary>
    /// <param name="array">The one-dimensional <see cref="T:System.Array"/> that is the destination of the elements copied from <see cref="T:System.Collections.ICollection"/>. The <see cref="T:System.Array"/> must have zero-based indexing.</param>
    /// <param name="index">The zero-based index in <paramref name="array"/> at which copying begins.</param>
    /// <exception cref="T:System.ArgumentNullException">
    /// 	<paramref name="array"/> is <see langword="null"/>.</exception>
    /// <exception cref="T:System.ArgumentOutOfRangeException">
    /// 	<paramref name="index"/> is less than zero.</exception>
    /// <exception cref="T:System.ArgumentException">
    /// 	<para>
    /// 		<paramref name="array"/> is multidimensional.</para>
    /// 	<para>-or-</para>
    /// 	<para>
    /// 		<paramref name="index"/> is equal to or greater than the length of <paramref name="array"/>.</para>
    /// 	<para>-or-</para>
    /// 	<para>The number of elements in the source <see cref="T:System.Collections.ICollection"/> is greater than the available space from <paramref name="index"/> to the end of the destination <paramref name="array"/>.</para>
    /// </exception>
    /// <exception cref="T:System.InvalidCastException">The type of the source <see cref="T:System.Collections.ICollection"/> cannot be cast automatically to the type of the destination <paramref name="array"/>.</exception>
    public void CopyTo(Script[] array, int index)
    {
      ReadScripts();
      scriptsList.CopyTo(array, index);
    }

    /// <summary>
    /// Gets an object that
    /// can be used to synchronize access to the <see cref="T:System.Collections.ICollection"/>.
    /// </summary>
    public object SyncRoot
    {
      get
      {
        return null;
      }
    }

    #endregion

    #region IRefreshable Members

    /// <summary>
    /// Refreshes the list of scripts.
    /// </summary>
    public void Refresh()
    {
      scriptsList = null;
    }

    #endregion
  }
}
